package com.yungee.logic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yungee.task.UploadFileHaweiTask;
import com.yungee.util.StringUtils;
import com.yungee.zhaosheng.entity.StudentCard;
import com.yungee.zhaosheng.service.impl.StudentCardServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;

@Service
@Slf4j
public class TransferFileLogic {
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private StudentCardServiceImpl studentCardService;

    public String transferFile(Long cardId) {
        StudentCard card = studentCardService.getById(cardId);
        if (card == null || StringUtils.isEmpty(card.getFileResource())){
            return "error";
        }
        String position = card.getFileResource().replace("/hongyu/picture/", "").replace(" ","");
        UploadFileHaweiTask uploadFileTask =  new UploadFileHaweiTask();
        String filePosition = "zhaosheng" + "/" + position;
        File file = new File(card.getFileResource());
        if (!file.exists()){
            StudentCard updateCard = new StudentCard();
            updateCard.setId(card.getId());
            updateCard.setFileResourceObsUrl("-");
            studentCardService.updateById(updateCard);
            return "file not exist";
        }
        uploadFileTask.setFile(new File(card.getFileResource()));
        uploadFileTask.setFilePosition(filePosition);
        uploadFileTask.setStudendCardId(card.getId());
        uploadFileTask.setStudentCardService(studentCardService);
        taskExecutor.execute(uploadFileTask);
        return "ok";
    }

    public void transferStudentCardFile() {
        QueryWrapper<StudentCard> studentCardQueryWrapper = new QueryWrapper<>();
        studentCardQueryWrapper.isNull("file_resource_obs_url");
        studentCardQueryWrapper.ne("file_resource", "");
        studentCardQueryWrapper.last(" limit 50");
        studentCardQueryWrapper.select("id");
        List<StudentCard> cardList = studentCardService.list(studentCardQueryWrapper);
        for (StudentCard card : cardList) {
            String transferFileResult = transferFile(card.getId());
            log.info("cardId:{},transferFileResult:{}", card.getId(), transferFileResult);
            try {
                Thread.sleep(300L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
